package com.dolphin.controller;

import com.dolphin.base.BaseController;
import com.dolphin.commons.Constants;
import com.dolphin.commons.IpUtil;
import com.dolphin.commons.OptionCacheUtil;
import com.dolphin.commons.utils.CookieUtils;
import com.dolphin.config.shiro.customToken.QqToken;
import com.dolphin.model.User;
import com.dolphin.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 描述:
 * ${DESCRIPTION}
 *
 * @author 小海豚
 * @create 2023-05-24 21:45
 * 个人博客地址：https://www.nonelonely.com
 */
@Controller
@RequestMapping("/qq")
public class QqLoginController extends BaseController {
    @Value("${shiro.timeout}")
    private Long timeout;
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String qqLogin(HttpServletRequest request, HttpServletResponse response, String url, Model model) throws IOException {
        CookieUtils.setCookie(response, "backUrl", url, -1);
        String callbackDomain = IpUtil.basePath(request).concat("qq/callback");
        String appId = OptionCacheUtil.getValue(Constants.QQ_APP_ID);
        if (appId == null || StringUtils.isEmpty(appId)) {
            model.addAttribute("statusCode", "500");
            model.addAttribute("msg", "APP_ID找不到嗯！o(￣︶￣)n");
            return view("static/admin/pages/exception/other.html");
        } else {
            return "redirect:https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id="
                    + appId + "&redirect_uri=" + callbackDomain + "&state=" + System.currentTimeMillis();
        }
    }


    @RequestMapping("/callback")
    public String qqCallback(HttpServletRequest request, HttpServletResponse response, String code, Model model) {
        Cookie cookie = CookieUtils.getCookie(request, "backUrl");
        String url = "/";
        if (cookie != null) {
            url = cookie.getValue();
        }
        // 1.获取Subject主体对象
        Subject subject = SecurityUtils.getSubject();
        // 2.封装用户数据
        QqToken token = new QqToken(code);
        // 3.执行登录，进入自定义Realm类中
        try {
            subject.login(token);
            User userByAccount = (User) subject.getPrincipal();
            userService.updateLastLoginTime(userByAccount);
            subject.getSession().setTimeout(timeout * 1000 * 60);
            if (userByAccount.hasAdminPage()) {
                return "redirect:/admin";
            } else {
                return "redirect:" + url;
            }
        } catch (LockedAccountException e) {
            model.addAttribute("statusCode", "500");
            model.addAttribute("msg", "该账号已被冻结");
            return view("static/admin/pages/exception/other.html");
        } catch (AuthenticationException e) {
            model.addAttribute("statusCode", "500");
            model.addAttribute("msg", "用户名或密码错误");
            return view("static/admin/pages/exception/other.html");
        } catch (Exception e) {
            model.addAttribute("statusCode", "500");
            model.addAttribute("msg", e.getMessage());
            return view("static/admin/pages/exception/other.html");
        }

    }
}
